<template>
	<view>
		<view class="page">
			<view class="item" style="display: flex;">
				<text>课程类型：</text>
				<radio-group>
					<view class="choice" v-for="(item,index) in optionList" :key="index" @click="selectOption(index)">
						<radio color="#FD973F" :checked="item.isSelect">{{item.name}}</radio>
					</view>
				</radio-group>
			</view>
			<view class="item">
				<text>课程名称：</text>
				<view class="content">
					<input type="text" value="" v-model="addForm.name" />
				</view>
			</view>

			<view class="item" v-if="isWeiKe">
				<text>微课类型：</text>
				<view class="content">
					<picker mode="selector" :value="1" :range="courseList" @change="bindPickerChange" range-key="name">
						<view>{{ courseList[index].name }}</view>
					</picker>
				</view>
			</view>
			<!-- 课程老师 -->
			<view class="item">
				<text>课程老师：</text>
				<view class="content">
					<input type="text" value="" v-model="addForm.teacher" />
				</view>
			</view>

			<view class="item">
				<text>课程价格：</text>
				<view class="content">
					<input type="text" value="" v-model="addForm.price" />
				</view>
			</view>
			<view class="item">
				<text>课程时长：</text>
				<view class="content">
					<input type="text" value="" v-model="addForm.classHour" />
				</view>
			</view>

			<view class="item">
				<text>课程简介：</text>
				<view class="content">
					<input type="text" value="" v-model="addForm.introduction" />
				</view>
			</view>
			<!-- 课程封面(竖屏) -->
			<view class="media" @click="chooseImage('imageUrl')">
				<text class="media_title">
					课程封面：\n(竖屏)
				</text>
				<view class="media_content">
					<image :src="addForm.imageUrl"></image>
				</view>
			</view>
			<!-- 课程封面(横屏) -->
			<view class="media" @click="chooseImage('poster')" v-if="isWeiKe">
				<text class="media_title">
					课程封面：\n(横屏)
				</text>
				<view class="media_content">
					<image :src="addForm.poster"></image>
				</view>
			</view>
			<!-- 上传视频 -->
			<view v-show="isVideo" v-for="(item, index) in addForm.video" :key="index">
				<view class="item">
					<text>小节名称：</text>
					<view class="content">
						<input type="text" value="" v-model="addForm.video[index].name" />
					</view>
					<image v-if="index == addForm.video.length-1" src="../../static/add.png"
						style="width: 40rpx;height: 40rpx;" @click="addSection(index+1)"></image>
					<image v-if="addForm.video.length" src="../../static/minus.png" style="width: 40rpx;height: 40rpx;"
						@click="deleteSection(index)"></image>
				</view>
				<view class="media">
					<view class="media_title">
						小节视频：
					</view>
					<view class="media_content" @click="chooseVideo(index)">
						<video v-if="addForm.video[index].video" :src="addForm.video[index].video" controls></video>
					</view>
				</view>
			</view>
			<!-- 每日一推 -->
			<view class="item" style="display: flex;" v-if="isWeiKe">
				<text>每日一推：</text>
				<radio-group style="width: 50%;display: flex;justify-content: space-around;">
					<radio color="#FD973F" @click="ifRecommended(true)" :checked="addForm.recommended">是</radio>
					<radio color="#FD973F" @click="ifRecommended(false)" :checked="!addForm.recommended">否</radio>
				</radio-group>
			</view>
			<!-- 热门课程 -->
			<view class="item" style="display: flex;" v-if="isWeiKe">
				<text>热门课程：</text>
				<radio-group style="width: 50%;display: flex;justify-content: space-around;">
					<radio color="#FD973F" @click="ifHost(true)" :checked="addForm.hot">是</radio>
					<radio color="#FD973F" @click="ifHost(false)" :checked="!addForm.hot">否</radio>
				</radio-group>
			</view>
		</view>

		<view class="addButton">
			<button @click="addCourse('draft')">存至草稿</button>
			<button @click="addCourse('send')">发布</button>
		</view>
	</view>
</template>

<script>
	import cloudbase from '@cloudbase/js-sdk';
	const db = cloudbase.database();
	const dbCmd = db.command;
	let that, _openid;
	let sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	export default {
		data() {
			return {
				isWeiKe: true,
				isVideo: true,
				optionList: [{
					name: '微课',
					isSelect: true
				}, {
					name: '校长课堂',
					isSelect: false
				}],
				index: 1,
				courseList: [{
					name: '钢琴'
				}, {
					name: '吉他'
				}, {
					name: '架子鼓'
				}, {
					name: '古筝'
				}, {
					name: '非洲鼓'
				}, {
					name: '主持'
				}, {
					name: '尤克里里'
				}, {
					name: '声乐'
				}],
				sourceType: ['拍摄', '相册', '拍摄或相册'],
				cameraList: [{
						value: 'back',
						name: '后置摄像头',
						checked: 'true'
					},
					{
						value: 'front',
						name: '前置摄像头'
					},
				],
				sourceTypeIndex: 2,
				cameraIndex: 0,
				addForm: {
					openId: getApp().globalData.userInfo.openId,
					admin: getApp().globalData.userInfo.power,
					name: '',
					introduction: '',
					imageUrl: '', //	封面图片
					poster: '', // 横屏封面
					classHour: '',
					price: '',
					discount: '', //折扣
					status: '', //课程状态:未发布、已发布
					institutionList: [], //存放购买的机构列表及他们的老师id，名称
					type: '', //课程类型：微课、文章、机构课程
					label: '', //微课类型：钢琴、吉他、架子鼓、古筝、其他
					classId: [],
					video: [{
						name: '',
						video: ''
					}], //课程视频
					article: [], //记录文章内容
					teacher: '', // 任课老师
					evaluate: [], // 课程评论
					recommended: false, // 每日一推
					hot: false, // 热门课程
				},
				fileList: [],
				videoFileList: [],
				refresh: true,

				tempFilePaths: [],
				videoTempFile: '',
				bufferList: [],

				teacherList: [],
				teacherIndex: 0,
			}
		},
		created() {
			this.videoFileList.length = 1;
		},
		onLoad(e) {
			that = this;
			_openid = getApp().globalData.userInfo._openid;
			// 获取参数
			if (e.item) {
				let course = JSON.parse(e.item);
				console.log(course);
				console.log(that.addForm.admin);
				// 初始化参数
				that.addForm = course;
				switch (course.type) {
					case '微课':
						that.optionList[0].isSelect = true;
						break;
					case '文章':
						that.optionList[1].isSelect = true;
						break;
					case '机构课程':
						that.optionList[2].isSelect = true;
						break;
				}
				switch (course.label) {
					case '钢琴':
						that.index = 0;
						break;
					case '吉他':
						that.index = 1;
						break;
					case '架子鼓':
						that.index = 2;
						break;
					case '古筝':
						that.index = 3;
						break;
					case '非洲鼓':
						that.index = 4;
						break;
					case '主持':
						that.index = 5;
						break;
					case '尤克里里':
						that.index = 6;
						break;
					case '声乐':
						that.index = 7;
						break;
				}
				// 初始化图片链接
				cloudbase.getTempFileURL({
					fileList: [that.addForm.imageUrl]
				}).then(res => {
					let list = res.fileList[0];
					this.addForm.imageUrl = list.tempFileURL;
				})
				cloudbase.getTempFileURL({
					fileList: [that.addForm.poster]
				}).then(res => {
					let list = res.fileList[0];
					this.addForm.poster = list.tempFileURL;
				})
				// 初始化视频链接
				that.addForm.video.forEach(item => {
					cloudbase.getTempFileURL({
						fileList: [item.video]
					}).then(res => {
						let list = res.fileList[0];
						item.video = list.tempFileURL;
					})
				})
			}
		},
		watch: {
			'addForm.type': function(newVal) {
				if (newVal == '微课') {
					this.isWeiKe = true;
					this.isVideo = true;
				} else if (newVal == '文章') {
					this.isWeiKe = false;
					this.isVideo = false;
				} else {
					this.isWeiKe = false;
					this.isVideo = true;
				}
			},
			'refresh': function(newVal) {
				let that = this;
				setTimeout(() => {
					that.refresh = true;
				}, 100)
			}

		},
		methods: {
			ifRecommended: function(flag) {
				if (flag) that.addForm.recommended = true;
				else that.addForm.recommended = false;
			},
			ifHost: function(flag) {
				if (flag) that.addForm.hot = true;
				else that.addForm.hot = false;
			},
			// 添加小节
			addSection: function(index) {
				that.addForm.video.push({
					name: '',
					video: ''
				})
			},
			deleteSection: function(index) {
				uni.showModal({
					title: '提示',
					content: '是否要删除此小节',
					success: (res) => {
						if (res.confirm) {
							let i = that.addForm.video.length;
							if (i > 1) {
								console.log(i);
								console.log(that.addForm.video.pop());
								console.log('确定删除');
							}
						} else if (res.cancel) {
							console.log('取消删除');
						}
					}
				})
			},
			//选择校长课堂上传，仅ADMIN有权限
			selectOption: function(index) {
				let that = this;
				that.addForm.admin = getApp().globalData.userInfo.power;
				console.log(that.addForm.admin);
				for (let i in that.optionList) {
					// that.optionList[i].isSelect = false;
					if (i == index) {
						if (i == 1 && that.addForm.admin == 'USER') {
							uni.showToast({
								title: '无权限上传',
								icon: 'none',
								duration: 2000
							});
						} else {
							that.optionList[i].isSelect = true;
							that.option = that.optionList[i].name;
							// console.log(that.option);
							that.addForm.type = that.optionList[i].name;
						}
					}
				}
				// console.log(that.optionList);
			},

			bindPickerChange: function(e) {
				// console.log(e);
				this.index = e.detail.value;
				this.addForm.label = this.courseList[e.detail.value].name;
				// console.log(this.addForm.label);
			},
			chooseImage: function(type) {
				let that = this;
				that.tempFilePaths = [];
				that.bufferList = [];
				that.fileList = [];
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success(res) {
						console.log('uploadImage:');
						console.log(res.tempFilePaths)
						that.tempFilePaths = res.tempFilePaths;
						that.setImageFileList(type);
					}
				})
			},
			chooseVideo: function(index) {
				console.log(index);
				let that = this;
				console.log('chooseVideo');
				that.tempFilePaths = [];
				that.bufferList = [];
				that.fileList = [];
				that.videoTempFile = '';
				// 上传视频
				console.log('上传视频');
				uni.chooseVideo({
					maxDuration: 10,
					count: 1,
					camera: that.cameraList[that.cameraIndex].value,
					sourceType: sourceType[that.sourceTypeIndex],
					success: (res) => {
						console.log(res);
						// console.log(JSON.stringify(res.tempFilePath), '视频')
						that.videoTempFile = res.tempFilePath;
						// console.log(that.videoTempFile);
						// this.src = res.tempFilePath;
						// console.log(this.src)

						that.setVideoFileList(index);

					}
				})
			},
			setImageFileList: function(type) {
				uni.showLoading({
					title: '上传中……'
				})
				// console.log(key);
				// console.log(length);
				let that = this;
				let str = that.randomString(5);
				cloudbase.uploadFile({
					cloudPath: "course/courseImage/" + str +
						".png",
					filePath: that.tempFilePaths[0],
					onUploadProgress: function(progressEvent) {
						console.log(progressEvent);
						var percentCompleted = Math.round(
							(progressEvent.loaded * 100) / progressEvent.total
						);
					}
				}).then(result => {
					// console.log(result)
					let i = new Object();
					that.tempFilePaths = [];
					i = result.fileID;
					that.bufferList.push(i);
					// 返回图片链接
					cloudbase.getTempFileURL({
						fileList: [that.bufferList[0]]
					}).then(res => {
						let list = res.fileList[0];
						if (type == 'imageUrl') {
							that.addForm.imageUrl = list.tempFileURL;
						} else {
							that.addForm.poster = list.tempFileURL;
						}
					})
					that.bufferList = [];
					uni.hideLoading();
				})
			},
			// 根据传的下标来赋值
			setVideoFileList: function(index) {
				uni.showLoading({
					title: '上传中……'
				})
				// console.log(key);
				// console.log(length);
				let that = this;

				that.bufferList = [];
				let str = that.randomString(5);
				cloudbase.uploadFile({
					cloudPath: "course/courseVideo/" + str +
						".mp4",
					filePath: that.videoTempFile,
					onUploadProgress: function(progressEvent) {
						let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent
							.total);
						console.log(percentCompleted);
					}
				}).then(result => {
					// console.log(result)
					let i = new Object();
					i = result.fileID;
					that.bufferList.push(i);
					cloudbase.getTempFileURL({
						fileList: [that.bufferList[0]]
					}).then(res => {
						let list = res.fileList[0];
						that.addForm.video[index].video = list.tempFileURL;
					})
					// console.log(that.addForm.video);
					uni.hideLoading();
				})
			},
			addCourse: function(e) {
				that.addForm.label = that.courseList[that.index].name;
				if (that.addForm.imageUrl == '' && type != '校长课堂') {
					uni.showToast({
						title: '封面图片不能为空',
						icon: 'error',
						duration: 1500
					})
					return;
				} else if (that.addForm.name == '' && type != '校长课堂') {
					uni.showToast({
						title: '课程名称不能为空',
						icon: 'error',
						duration: 1500
					})
					return;
				} else if (that.addForm.video == '' && type != '校长课堂') {
					uni.showToast({
						title: '课程视频不能为空',
						icon: 'error',
						duration: 1500
					})
					return;
				}
				that.addForm.status = e == 'send' ? '已发布' : '未发布';
				// 判断是修改还是添加
				if (that.addForm._id != null) {
					console.log(that.addForm.imageUrl);
					cloudbase.database().collection('course').where({
						_id: that.addForm._id
					}).update({
						name: that.addForm.name,
						introduction: that.addForm.introduction,
						imageUrl: that.addForm.imageUrl,
						poster: that.addForm.poster,
						classHour: that.addForm.classHour,
						price: that.addForm.price,
						discount: that.addForm.discount,
						status: that.addForm.status,
						institutionList: that.addForm.institutionList,
						type: that.addForm.type,
						label: that.addForm.label,
						classId: that.addForm.classId,
						video: that.addForm.video,
						article: that.addForm.article,
						teacher: that.addForm.teacher,
						recommended: that.addForm.recommended,
						hot: that.addForm.hot
					}).then(res => {
						console.log(res);
						let pages = getCurrentPages();
						let prePage = pages[pages.length - 2];
						prePage.onLoad();
						// 返回上一页
						uni.navigateBack({
							delta: 1
						})
					})
				} else {
					cloudbase.database().collection('course').add({
						openId: that.addForm.openId,
						name: that.addForm.name,
						introduction: that.addForm.introduction,
						imageUrl: that.addForm.imageUrl,
						poster: that.addForm.poster,
						classHour: that.addForm.classHour,
						price: that.addForm.price,
						discount: that.addForm.discount,
						status: that.addForm.status,
						institutionList: that.addForm.institutionList,
						type: that.addForm.type,
						label: that.addForm.label,
						classId: that.addForm.classId,
						video: that.addForm.video,
						article: that.addForm.article,
						teacher: that.addForm.teacher,
						recommended: that.addForm.recommended,
						hot: that.addForm.hot
					}).then(res => {
						console.log(res);
						let pages = getCurrentPages();
						let prePage = pages[pages.length - 2];
						prePage.onLoad();
						// 返回上一页
						uni.navigateBack({
							delta: 1
						})
					})
				}
			},
			add: function() {
				this.videoFileList.length++;
				this.refresh = false;
			},
			getUrl: function(e) {
				// let that = this;
				// that.insInformation.imageUrl = [];
				cloudbase.getTempFileURL({
					fileList: e
				}).then(res => {
					// console.log(res);
					let list = res.fileList;
					console.log(list);
					// console.log(that.carouselList)
				})
			},
			// 取名用 随机
			randomString: function(e) {
				e = e || 32;
				let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
				let a = t.length;
				let n = "";
				for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
				return n
			},
			bindPickerTeacher: function() {
				this.teacherIndex = e.detail.value;
				this.addForm.teacher.name = this.teacherList[e.detail.value].name;
				this.addForm.teacher.id = this.teacherList[e.detail.value].id;
			},
		}
	}
</script>

<style>
	page {
		background-color: #F3F5F7;
	}

	.page {
		margin-bottom: 60rpx;
		/* height: 2300rpx; */
		/* height: 1020rpx; */
		/* padding-bottom: 60px; */
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		margin: 10rpx 30rpx;
	}

	.item {
		margin: 15rpx 0rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: #222222;
		display: flex;
		/* display: inline-block; */
	}

	.item text {
		width: 150rpx;
		margin-top: 15rpx;
	}

	.item image {
		width: 40rpx;
		height: 40rpx;
		vertical-align: middle;
		margin-top: 15rpx;
		margin-left: 10rpx;
	}

	.content {
		width: calc(90% - 200rpx);
		background-color: #fff;
		border-radius: 16rpx;
		padding: 15rpx 0rpx;
		text-align: center;
		height: 40rpx;
		color: #555;
	}

	.choice {
		width: 220rpx;
		height: 30rpx;
		font-size: 26rpx;
		line-height: 30rpx;
		display: inline-block;
		color: #666666;
	}

	.choice_notSelect {
		width: 28rpx;
		height: 28rpx;
		margin-right: 14rpx;
		border-radius: 50%;
		border: 1px solid #FD973F;
		vertical-align: middle;
		display: inline-block;
	}

	.choice_select {
		width: 28rpx;
		height: 28rpx;
		margin-right: 14rpx;
		border-radius: 50%;
		border: 1px solid #FD973F;
		vertical-align: middle;
		display: inline-block;
		background-color: #FD973F;
	}

	.addButton {
		display: flex;
		margin-top: 100rpx;
		margin-bottom: 60rpx;
	}

	.addButton button {
		background-color: #FD973F;
		color: #fff;
		width: 250rpx;
		border-radius: 16rpx;
	}

	.addButton_item {
		width: 270rpx;
		margin-right: 30rpx;
		text-align: center;
		color: #FFFFFF;
		background-color: #FD973F;
		display: inline-block;
		border-radius: 30rpx;
	}

	.media {
		width: 702rpx;
		height: 300rpx;
		margin-top: 42rpx;
		margin-right: auto;
		margin-left: auto;
		font-size: 30rpx;
		font-weight: 500;
		line-height: 42rpx;
		color: #222222;
		/* display: inline-block; */
	}

	.media_title {
		float: left;
		width: 150rpx;
		height: 42rpx;
		font-size: 30rpx;
		line-height: 42rpx;
		color: #222222;
	}

	.media_content {
		float: left;
		width: 450rpx;
		height: 300rpx;
		/* margin-right: 60rpx; */
		background-color: #000000;
	}

	.media_content image {
		/* float: left; */
		width: 450rpx;
		height: 300rpx;
		margin-right: 60rpx;

	}

	.media_content video {
		/* float: left; */
		width: 450rpx;
		height: 300rpx;
		margin-right: 60rpx;

	}

	.media_addButton {
		float: left;
		width: 100rpx;
		height: 60rpx;
		padding-left: 20rpx;
		box-sizing: border-box;
	}

	.media_addButton image {
		/* float: left; */
		width: 50rpx;
		height: 50rpx;
	}
</style>
